package com.soup.lab.executor.pool2;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.ListIterator;

/**
 * 决定任务是进行排队，还是直接执行
 */
public class QueuedRunner {

    private List<Node> runningNodes = Lists.newArrayList();

    private KeyWaitingPolicy waitingPolicy;

    public QueuedRunner() {
        this(KeyWaitingPolicy.DEFAULT_WAITING_POLICY);
    }

    public QueuedRunner(KeyWaitingPolicy waitingPolicy) {
        this.waitingPolicy = waitingPolicy;
    }

    public Runnable apply(KeyPickRunnable r) {
        synchronized (this) {
            Node temp;
            ListIterator<Node> listIterator = runningNodes.listIterator(runningNodes.size() - 1);
            while (listIterator.hasPrevious()) {
                temp = listIterator.previous();
                if(!temp.isAlive()) {
                    listIterator.remove();
                    continue;
                }
                if(waitingPolicy.ifWaiting(r.getKeys(), temp.waitingKeySet())) {
                    temp.add(r);
                    return null;
                }
            }
            return new Node(r);
        }
    }

}
